package com.orhanobut.hawk.parser

import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import java.lang.reflect.Type

class GsonParser(private val gson: Gson) : Parser {
  override fun <T> fromJson(content: String?, type: Type): T? {
    if (content.isNullOrEmpty()) return null
    return gson.fromJson(content, type)
  }

  override fun <T> fromJson(content: String, clazz: Class<*>?): T? {
    if (clazz == null) return null
    return try {
      @Suppress("UNCHECKED_CAST")
      gson.fromJson(content, clazz) as T?
    } catch (e: JsonSyntaxException) {
      null
    }
  }

  override fun toJson(body: Any): String = gson.toJson(body)
}